package com.parse.ip.parseip.service.impl;

import com.alibaba.fastjson.JSON;
import com.parse.ip.parseip.entity.City;
import com.parse.ip.parseip.mapper.ParseIpMapper;
import com.parse.ip.parseip.service.ParseIpService;
import com.parse.ip.parseip.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class ParseIpServiceimpl implements ParseIpService {
   public static Logger logger = LoggerFactory.getLogger(ParseIpServiceimpl.class);
    @Autowired
    private ParseIpMapper mapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void save(String network) {
        //解析networkjson字符串
        //{"27.195.157.210":{"iP":"27.195.157.210","network":"山东省淄博市 联通"}}
        Map<String,Object> map = JSON.parseObject(network);
        //存到Redis中一份数据,并设置时效
        for(Map.Entry<String,Object> entry : map.entrySet()){

            City city = new City();
            City city1 = mapper.queryByIp(entry.getKey());
            if(city1 != null){
                logger.info("数据库已存储过这个ip-->"+entry.getKey());
                return;
            }

            city.setId(UUID.randomUUID().toString().replace("-",""));
            city.setIP(entry.getKey());
            city.setPlace(JSON.toJSONString(entry.getValue()));
            city.setCreateTime(new Date());

            redisUtil.set(entry.getKey(),entry.getValue(),1000*60*24*7);//存入redis

            mapper.save(city);
            logger.info("ip解析成功并入库-->"+network);
        }

    }

    @Override
    public Object getNetwork(String ip) {
        //根据ip查询归属地,先从redis缓存中去值,redis中没有再从数据库中取值存到redis中
        Object object = redisUtil.get(ip);
        if(object == null){
            logger.info("redis缓存ip失效读取数据库数据-->"+ip);
            City city = mapper.queryByIp(ip);
            redisUtil.set(ip,JSON.parseObject(city.getPlace()),1000*60*24*7);
            return redisUtil.get(ip);
        }
        logger.info("读取redis缓存数据"+ip);
        return object;
    }
}
